<template>
  <a-modal
    :title="mdlStatus=='add'?'上传':'修改'"
    :width="640"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok') }"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['id', { initialValue: 0 }]" disabled />
        </a-form-item>
        <!-- <a-form-item label="描述">
          <a-input v-decorator="['description', {rules: [{required: true, min: 5, message: '请输入至少五个字符的规则描述！'}]}]" />
        </a-form-item> -->

        <a-form-item label="平台">
          <a-select 
            placeholder="请选择平台" 
            v-decorator="[ 'tagNameId', {rules: [{ required: true, message: '请选择平台！'}]} ]"
            @change="()=> form.setFieldsValue({
              internalStorage: undefined
            })">
            <a-select-option 
              v-for="item in platformOptions"
              :key="item.value"
              :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="版本号">
          <a-input v-decorator="['versionNumber', {rules: [{required: true, message: '请输入版本号！'}]}]" />
        </a-form-item>
        <a-form-item label="产物类型">
          <a-select 
            placeholder="请选择产物类型" 
            :disabled="!form.getFieldValue('tagNameId')"
            v-decorator="[ 'internalStorage', {rules: [{ required: true, message: '请选择产物类型！'}]} ]">
            <a-select-option 
              v-for="item in getMemoryOptions(form.getFieldValue('tagNameId'))"
              :key="item"
              :value="item">{{ item }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="上传文件">
          <!-- <a-button @click="upload2">上传</a-button> -->
          <!-- <a-button id="uploadFile" ref="file" type="file" @change="uploadWithSDK">上传</a-button> -->
          <a-upload
            v-decorator="[ 'resourcesPath' ]"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :remove="handleRemove"
            accept=".zip,.fup"
            @change="uploadWithSDK"
          >
            <a-button
            :disabled="disableUpload()">
              <a-icon type="upload" />上传
            </a-button>
          </a-upload>
          <div v-if="initUrl && getUrlKey(initUrl)">
            <a-tag closable @close="delFile">{{ getUrlKey(initUrl) }}</a-tag>
          </div>
          <!-- <div :v-show="controlUploadBtn">
            <a-progress :percentage="uploadProgress" v-if="uploadProgress != 0 &&uploadProgress != 100"></a-progress>
            <a-button @click="controlUpload" v-if="uploadProgress != 0 &&uploadProgress != 100">{{uploadStatus?'暂停上传':'继续上传'}}</a-button>
          </div> -->
          <!-- <global-uploader
            ref="uploaderRef"
            :global="false"
            :params="{page: 'home'}"
            :options="{target: 'http://10.0.0.10'}"
            @fileAdded="fileAdded"
          /> -->
        </a-form-item>
        <a-form-item label="备注（可选）">
          <a-textarea v-decorator="['msg', {rules: [{required: false, message: '请输入备注！'}]}]" />
          <!-- <a-textarea v-model:value="value" placeholder="Basic usage" :rows="4" /> -->
        </a-form-item>
        <a-form-item label="版本说明">
          <a-textarea v-decorator="['imprint', {rules: [{required: false, message: '请输入版本说明！'}]}]" />
          <!-- <a-textarea v-model:value="value" placeholder="Basic usage" :rows="4" /> -->
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import Bus from '@/components/vue-simple-uploader/js/bus'
import GlobalUploader from '@/components/vue-simple-uploader/GlobalUploader'
import { mergeSimpleUpload, getQNToken } from '@/api/updata'
import * as qiniu from 'qiniu-js'
import { mapActions, mapGetters } from 'vuex'
import { getTagNameList } from '@/api/platform'
import { UserOutlined, InfoCircleOutlined } from '@ant-design/icons-vue';

// 表单字段
const fields = ['description', 'id']

export default {
  components: {
    GlobalUploader,
    InfoCircleOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    mdlStatus:{
      type: String,
      default: () => 'add'
    },
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    
    return {
      form: this.$form.createForm(this),

      controlUploadBtn: true,
      subscription: '',
      uploadProgress: 0,
      uploadStatus: false,

      fileList: [],
      platformOptions: [],
      memoryOptions: [],

      initUrl:'',
    }
  },
  watch: {
    visible:{
      handler(val) {
        this.fileList = []
        this.initUrl = ''
      },
      deep: true,
    },
    model: {
      handler(val) {
        console.log('%c [ val ]-156', 'font-size:13px; background:pink; color:#bf2c9f;', val)
        if(val && val.resourcesPath && val.resourcesPath.toString() != '[]')this.initUrl = val.resourcesPath
        // 解析val中的resourcesPath字段，该字段为文件访问的url链接，将该url转为file
        this.$nextTick(()=> {
          this.form.setFieldsValue(val);
        })
      },
      deep: true,
    }
  },
  computed: {
    ...mapGetters(['getUploadList']),
  },
  created () {
    this.initOptions();
    console.log('custom modal created')

    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  mounted () {
    // 文件选择后的回调
    Bus.$on('fileAdded', () => {
      console.log('文件已选择')
    })

    // 文件上传成功的回调
    Bus.$on('fileSuccess', () => {
      console.log('文件上传成功')
    })
  },

  beforeDestroy () {
    Bus.$off('fileAdded')
    Bus.$off('fileSuccess')
  },

  methods: {
    ...mapActions(['pushUploadItem']),
    disableUpload() {
      const obj = this.getUploadList
      for (const key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          const element = obj[key];
          if(element.uploadSize != element.fileSize) {
            return true;
          }
        }
      }
      return false
    },
    delFile(){
      this.initUrl = ''
      this.form.setFieldsValue({
        resourcesPath: ''
      });
      console.log('this.form.resourcesPath', this.form)
    },
    getUrlKey(e){
      console.log('%c [ e ]-207', 'font-size:13px; background:pink; color:#bf2c9f;', e)
      if(!e || e.toString() == []) return ''
      let a1 = e.split('?')[0]
      let a2 = a1.split('/')
      if(!a2) return ''
      return a2[a2.length-1]
    },
    async initOptions() {
      const { data } = await getTagNameList({
        name: "",
        page: 0,
        pageNum: 1,
        pageSize: 10000,
        tagSystem: ""
      });
      this.platformOptions = data?.data?.map(i=> {
        return {
          label: i.name,
          value: i.id,
          memoryOptions: JSON.parse(i.supports || '[]'),
        }
      })
    },
    getMemoryOptions(platformId) {
      const findData = this.platformOptions.find(i=> i.value == platformId);
      return findData?.memoryOptions;
    },
    upload2 (e) {
      // this.$refs.uploaderRef()
      // 打开文件选择框
      // this.$nextTick(function () {
        // DOM 现在更新了
        Bus.$emit('openUploader')
      // })
    },
    // 自定义7牛上传
    async uploadWithSDK (e) {
      this.initUrl = '';
      // this.pushUploadItem({
      //   file: e.file
      // })
    },
    async uploadWithSDK2 (e) {
      console.log('🚀 ~ file: CreateForm.vue:165 ~ uploadWithSDK ~ e:', e)
      console.log('开始')
      const _self = this
      _self.uploadProgress = 0
      _self.uploadStatus = false
      // let file = document.getElementById("uploadFile").files[0];
      const file = e.file
      // if(file.type != 'video/mp4'){
      //     alert("最大上传文件1G");
      //     return false;
      // }
      if (file.size > 1 * 1024 * 1024 * 1024) {
          alert('最大上传文件1G')
          return false
      }
      // 获取上传token。
      const { data } = await getQNToken()
      // console.log('data', data)
      // const {data} = await mergeSimpleUpload()
      // let uploadToken = data
      const uploadToken = data

      if (!file) { return }
      let compareChunks = []
      var finishedAttr = []
      // 基础配置 [详情](https://developer.qiniu.com/kodo/1283/javascript)
      const config = {
          checkByServer: true,
          checkByMD5: true,
          forceDirect: false,
          useCdnDomain: true,
          disableStatisticsReport: false,
          retryCount: 6,
          region: qiniu.region.z2,
          debugLogLevel: 'INFO'
      }
      const putExtra = {
          customVars: {}
      }
      const name = file.name
      putExtra.customVars['x:name'] = name.split('.')[0] // 文件名称
      console.log('-------------')
      console.log('file', file)
      console.log('name', name)
      console.log('uploadToken', uploadToken)
      console.log('putExtra', putExtra)
      console.log('config', config)
      console.log('-------------')
      console.log('qiniu.upload', qiniu)
      const observable = qiniu.upload(file, name, uploadToken, putExtra, config)
      console.log('observable', observable)
      var next = function (response) {
        console.log('response', response)
          var chunks = response.chunks || []
          var total = response.total
          // 这里对每个chunk更新进度，并记录已经更新好的避免重复更新，同时对未开始更新的跳过
          for (var i = 0; i < chunks.length; i++) {
              if (chunks[i].percent === 0 || finishedAttr[i]) {
                  continue
              }
              if (compareChunks[i].percent === chunks[i].percent) {
                  continue
              }
              if (chunks[i].percent === 100) {
                  finishedAttr[i] = true
              }
              console.log(chunks[i].percent)
          }
          compareChunks = chunks
          // console.log("总进度：", total.percent);
          _self.uploadProgress = _self.toDecimal2(total.percent)
      }
      var error = function (error) {
        console.log('error', error)
          _self.$message.error('上传出错!')
      }
      var complete = function (res) {
          console.log('res: ', res)
          // _self.completeFileUrl = `${_self.qiniuaddr}/${res.key}`;
          _self.ruleForm.gcjsyxcl = {
              url: `${_self.qiniuaddr}/${res.key}`,
              fileName: name
          }
          _self.$message.success('上传成功!')
      }
      // 设置next,error,complete对应的操作，分别处理相应的进度信息，错误信息，以及完成后的操作
      var subObject = {
          next: next,
          error: error,
          complete: complete
      }
      _self.controlUpload = function () {
          // _self.addUploadBoard(file);
          _self.uploadStatus = !_self.uploadStatus
          if (_self.uploadStatus) {
              _self.subscription = observable.subscribe(subObject) // 调用sdk上传接口获得相应的observable，控制上传和暂停
          } else {
              _self.subscription.unsubscribe()
          }
      }
      _self.controlUpload()
    },
    beforeUpload (e) {
      this.form.setFieldsValue({
        resourcesPath: [e]
      });
      this.fileList = [e]
      return false
    },
    handleRemove() {
      this.form.setFieldsValue({
        resourcesPath: []
      });
      this.fileList = []
    }
  }
}
</script>
